package com.siyoumi.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.WxUser;
import com.siyoumi.app.entity.WxUserInfo;
import com.siyoumi.app.mapper.WxUserInfoMapper;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.util.XReturn;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.util.XStr;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//t_wx_user_a_info
@Service
public class WxUserInfoService
        extends ServiceImplBase<WxUserInfoMapper, WxUserInfo> {
    static public WxUserInfoService getBean() {
        return XSpringContext.getBean(WxUserInfoService.class);
    }

    public WxUserInfo getByOpenid(String openid) {
        String key = XStr.concat(getEntityName(), openid);
        return XHttpContext.getAndSetData(key, k ->
        {
            QueryWrapper<WxUserInfo> query = q().eq("winfo_openid", openid)
                    .eq(fdX(), XHttpContext.getX());
            return first(query);
        });
    }

    public XReturn saveEntity(InputData inputData) {
        List<String> ignoreField = new ArrayList<>();
        ignoreField.add("winfo_id");
        ignoreField.add("winfo_x_id");
        ignoreField.add("winfo_openid");
        ignoreField.add("winfo_member_level");

        return saveEntity(inputData, false, ignoreField);
    }

    public XReturn saveEntityAfter(InputData inputData, WxUserInfo entity) {
        WxUserService appWxUser = WxUserService.getBean();
        WxUser entityWxUser = appWxUser.getByOpenid(entity.getWinfo_openid());
        //同步更新wx_user表
        WxUser entityWxUserUpdate = new WxUser();
        entityWxUserUpdate.setWxuser_true_name(entity.getWinfo_name());
        if (XStr.hasAnyText(entity.getWinfo_phone())) {
            entityWxUserUpdate.setWxuser_phone(entity.getWinfo_phone());
        }
        appWxUser.saveOrUpdatePassEqualField(entityWxUser, entityWxUserUpdate);

        XReturn r = XReturn.getR(0);
        r.setData("user", entity);
        return r;
    }
}
